package com.example.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.experimental.UtilityClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


public final class JsonUtil {

    private static ObjectMapper M;

    /* 禁止 new */
    private JsonUtil() {}

    @Autowired
    public static void setObjectMapper(ObjectMapper mapper) {
        M = mapper;
    }
    // Spring 启动时把已经配置好的单例 ObjectMapper 灌进来

     /**
     * 把任意 Object 转成 List<T>，全程不抛 NPE
     *
     * @param obj 可能是 List、Map、JSON 字符串，甚至 null
     * @param clz 目标元素类型
     * @param <T> 元素类型
     * @return 非 null 的 List<T>（结构不对时返回空集合）
     */
    public static <T> List<T> toList(Object obj, Class<T> clz) {
        if (M == null) {
            throw new IllegalStateException("ObjectMapper not initialized. Make sure JsonUtil is managed by Spring.");
        }

        if (obj == null) {
            return Collections.emptyList();
        }
        try {
            // 1. 字符串 -> JsonNode
            if (obj instanceof String) {
                obj = M.readTree((String) obj);
            }

            // 2. 单个 Map -> 单对象 -> 包成 List
            if (obj instanceof Map) {
                T one = M.convertValue(obj, clz);
                return Collections.singletonList(one);
            }

            // 3. 数组/集合 -> List<T>
            if (obj instanceof List) {
                JavaType type = M.getTypeFactory().constructCollectionType(List.class, clz);
                return M.convertValue(obj, type);
            }

            // 4. 兜底尝试
            JavaType type = M.getTypeFactory().constructCollectionType(List.class, clz);
            return M.convertValue(obj, type);
        } catch (Exception e) {
            // 结构不匹配、字段对不上、泛型错误等一律返回空集合
            return Collections.emptyList();
        }
    }

    /**
     * 万能转换：object → List<T>，字段对上就映射，对不上就跳过，0 异常
     */
    public static  <T> List<T> objToList(Object obj, Class<T> clazz) {
        if (M == null) {
            throw new IllegalStateException("ObjectMapper not initialized. Make sure JsonUtil is managed by Spring.");
        }
        if (obj == null) return Collections.emptyList();
        try {
            // 1. 先统一变成 List<JsonNode>，避免单个 Map 特殊处理
            List<JsonNode> nodes;
            if (obj instanceof String) {
                JsonNode tree = M.readTree((String) obj);
                nodes = tree.isArray() ? M.convertValue(tree, new TypeReference<List<JsonNode>>() {})
                        : Collections.singletonList(tree);
            } else if (obj instanceof Map) {
                nodes = Collections.singletonList(M.valueToTree(obj));
            } else if (obj instanceof List) {
                nodes = M.convertValue(obj, new TypeReference<List<JsonNode>>() {});
            } else {
                nodes = Collections.singletonList(M.valueToTree(obj));
            }

            // 2. 每个 JsonNode → 只保留目标类存在的字段
            return nodes.stream()
                    .map(node -> M.convertValue(node, clazz)) // 只对得上字段的才会赋值
                    .collect(Collectors.toList());
        } catch (Exception e) {
            return Collections.emptyList();
        }
    }

}
